package com.ecar.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtilsBean;


public class DataValidateUtil {
	/**
	 * 处理object以下属性中,存在null值
	 * @param obj
	 * @return
	 */
	public static Object parseNull(Object obj) {
		try {
			PropertyUtilsBean b = new PropertyUtilsBean();
				Map map = b.describe(obj);
				Iterator it = map.keySet().iterator();
				while (it.hasNext()) {
					String key = it.next().toString();
					if(map.get(key) == null){
						if(b.getPropertyType(obj, key) == String.class)
							b.setProperty(obj, key.toString(), "");
						else if(b.getPropertyType(obj, key) == Integer.class || b.getPropertyType(obj, key) == int.class)
							b.setProperty(obj, key.toString(), 0);
						else if(b.getPropertyType(obj, key) == Long.class || b.getPropertyType(obj, key) == long.class)
							b.setProperty(obj, key.toString(), 0l);
						else if(b.getPropertyType(obj, key) == Double.class || b.getPropertyType(obj, key) == double.class)
							b.setProperty(obj, key.toString(), 0.00);
					/*	else if(b.getPropertyType(obj, key) == Date.class)
							b.setProperty(obj, key.toString(), "");*/
						/*else {
							Class<?> c = b.getPropertyType(obj, key).getClass();
							b.setProperty(obj, key.toString(), c.newInstance());
						}*/
							
					}
				}
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
	
	/**
	 * 
	 * @author fire
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	 public static Map<String, Object> objectToMap(Object obj) {    
	        if(obj == null){    
	            return null;    
	        }   
	        obj= parseNull(obj);
	        
	        Map<String, Object> map = new HashMap<String, Object>();    
	  
	        try {
				Field[] declaredFields = obj.getClass().getDeclaredFields();    
				for (Field field : declaredFields) {    
				    field.setAccessible(true);  
				    map.put(field.getName(), field.get(obj));  
				}
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}    
	  
	        return map;  
	    }   
}
